package com.imis.base.filter;

import com.imis.base.constant.DataBaseConstant;
import com.imis.base.constant.enums.CommonResponseEnum;
import com.imis.base.util.ConvertUtils;
import com.imis.base.util.CurrentUserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * DataPermissionFilter<br>
 * 数据权限过滤器
 * </p>
 *
 * @author XinLau
 * @version 1.0
 * @since 2020年10月16日 15:40
 */
@Component
@Slf4j
public class DataPermissionFilter extends OncePerRequestFilter {

    /**
     * 内部过滤
     *
     * @param httpServletRequest  - 请求
     * @param httpServletResponse - 响应
     * @param filterChain         - 过滤链
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/10/16 16:49
     */
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // 获取超级查询参数（请求的接口标识）
        String param = httpServletRequest.getParameter(DataBaseConstant.SUPER_QUERY_PARAMS);
        if (ConvertUtils.isEmpty(param)) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } else {
            String token = CurrentUserUtils.getTokenFormHttpServletRequest();
            // 1、判断是否登录
            CommonResponseEnum.ERROR_NO_TOKEN.assertNotNull(token);
            // 2、生成超级查询参数
            Map<String, Object> parameterMap = new HashMap<>(1);
            parameterMap.put(DataBaseConstant.SUPER_QUERY_PARAMS, generateSuperQueryParams(param, token));
            // 3、请求参数修改
            RequestParameterWrapper requestParameterWrapper = new RequestParameterWrapper(httpServletRequest);
            requestParameterWrapper.addParameters(parameterMap);
            filterChain.doFilter(requestParameterWrapper, httpServletResponse);
        }
    }

    /**
     * 生成超级查询参数
     *
     * @param param - 参数（请求的接口）
     * @param token - 当前登录用户的Token
     * @return String[]  - 级查询参数
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/10/16 16:45
     */
    private String[] generateSuperQueryParams(final String param, final String token) {
        String structuredQueryLanguage = "";
        return new String[]{structuredQueryLanguage};
    }

}
